<script lang="ts" setup>
import Codemirror from 'codemirror-editor-vue3'
// 编辑器代码格式
import 'codemirror/mode/javascript/javascript.js'
// 自动刷新(防止codemirror需要手动刷新才出数据)
import 'codemirror/addon/display/autorefresh'
// 主题
import 'codemirror/theme/ayu-mirage.css'
import useNotice from '@/hooks/useNotic'
import { useVModel } from '@vueuse/core'
import { computed } from 'vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  // 代码框高度
  height: {
    type: String,
    default: '300px'
  },
  // 是否禁用编辑
  disabled: {
    type: Boolean,
    default: false
  }
})
const emits = defineEmits(['update:modelValue'])

const codeSnippets = useVModel(props, 'modelValue', emits)
const cmOptions = computed(() => {
  return {
    autorefresh: true,
    tabSize: 2,
    mode: 'text/javascript',
    theme: 'ayu-mirage',
    line: true,
    viewportMargin: Infinity, //处理高度自适应时搭配使用
    highlightDifferences: true,
    autofocus: false,
    indentUnit: 2,
    smartIndent: true,
    readOnly: props.disabled, // 只读
    showCursorWhenSelecting: true,
    firstLineNumber: 1
  }
})

/**
 * 格式化JSON
 */
function handlerFormatJSON() {
  try {
    codeSnippets.value = JSON.stringify(JSON.parse(props.modelValue), null, 2)
  } catch (error) {
    useNotice().warning(`格式化出错:${error}`)
  }
}
</script>

<template>
  <div class="db-code-json-bg">
    <el-button class="db-code-json-btn" type="primary" @click="handlerFormatJSON">格式化JSON</el-button>
    <div class="db-code-json-box" :style="`height: ${height}`">
      <Codemirror v-model:value="codeSnippets" :options="cmOptions" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.db-code-json-bg {
  width: 100%;
  display: flex;
  flex-direction: column;
  .db-code-json-btn {
    width: 120px;
  }
  .db-code-json-box {
    margin-top: 4px;
  }
}
</style>
